﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using PersonaLibrary.ViewModel;
using PersonaLibrary.ViewModel.CollectionViewModel;

namespace PersonaLibrary.View
{
	public sealed class VmDataTemplateSelector : DataTemplateSelector
	{
		private const string ViewNameFormat = "PersonaLibrary.View.{0}View.{0}View, PersonaLibrary";

		public override DataTemplate SelectTemplate(object item, DependencyObject container)
		{
			if (item != null)
			{
				Type itemType = item.GetType();

				string viewTypeName;

				if (itemType.IsGenericType)
					viewTypeName = string.Format(ViewNameFormat, itemType.Name.Remove(itemType.Name.Length - 11));
				else
					viewTypeName = string.Format(ViewNameFormat, itemType.Name.Remove(itemType.Name.Length - 9));

				FrameworkElementFactory userControll = new FrameworkElementFactory(Type.GetType(viewTypeName));
				DataTemplate result = new DataTemplate {VisualTree = userControll};

				return result;
			}

			return base.SelectTemplate(item, container);
		}
	}
}
